/*!
 * \file test_signal_hook_comprehensive.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/19
 * 
 * \brief 信号钩子综合测试文件
 * 测试信号处理、回调机制等功能
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <memory>
#include <string>
#include <vector>
#include <thread>
#include <chrono>
#include <atomic>
#include <functional>
#include <signal.h>
#include <map>
#include <mutex>
#include <condition_variable>
#include <queue>

// 信号钩子系统的模拟实现
class SignalHook {
public:
    using SignalHandler = std::function<void(int)>;
    
    static SignalHook& getInstance() {
        static SignalHook instance;
        return instance;
    }
    
    // 注册信号处理器
    bool registerHandler(int signal, SignalHandler handler) {
        std::lock_guard<std::mutex> lock(mutex_);
        handlers_[signal] = handler;
        
        // 设置系统信号处理器
        struct sigaction sa;
        sa.sa_handler = &SignalHook::staticSignalHandler;
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = 0;
        
        return sigaction(signal, &sa, nullptr) == 0;
    }
    
    // 注销信号处理器
    bool unregisterHandler(int sig) {
        std::lock_guard<std::mutex> lock(mutex_);
        handlers_.erase(sig);
        
        // 恢复默认信号处理
        return ::signal(sig, SIG_DFL) != SIG_ERR;
    }
    
    // 触发信号处理（用于测试）
    void triggerHandler(int signal) {
        std::lock_guard<std::mutex> lock(mutex_);
        auto it = handlers_.find(signal);
        if (it != handlers_.end()) {
            it->second(signal);
        }
    }
    
    // 获取已注册的信号数量
    size_t getHandlerCount() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return handlers_.size();
    }
    
    // 检查信号是否已注册
    bool isHandlerRegistered(int signal) const {
        std::lock_guard<std::mutex> lock(mutex_);
        return handlers_.find(signal) != handlers_.end();
    }
    
    // 清除所有处理器
    void clearAllHandlers() {
        std::lock_guard<std::mutex> lock(mutex_);
        for (const auto& pair : handlers_) {
            ::signal(pair.first, SIG_DFL);
        }
        handlers_.clear();
    }

private:
    SignalHook() = default;
    ~SignalHook() {
        clearAllHandlers();
    }
    
    static void staticSignalHandler(int signal) {
        getInstance().triggerHandler(signal);
    }
    
    mutable std::mutex mutex_;
    std::map<int, SignalHandler> handlers_;
};

// 信号事件记录器
class SignalEventRecorder {
public:
    struct SignalEvent {
        int signal;
        std::chrono::system_clock::time_point timestamp;
        std::thread::id thread_id;
    };
    
    void recordSignal(int signal) {
        std::lock_guard<std::mutex> lock(mutex_);
        events_.push_back({
            signal,
            std::chrono::system_clock::now(),
            std::this_thread::get_id()
        });
    }
    
    std::vector<SignalEvent> getEvents() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return events_;
    }
    
    void clear() {
        std::lock_guard<std::mutex> lock(mutex_);
        events_.clear();
    }
    
    size_t getEventCount() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return events_.size();
    }
    
    size_t getEventCount(int signal) const {
        std::lock_guard<std::mutex> lock(mutex_);
        return std::count_if(events_.begin(), events_.end(),
            [signal](const SignalEvent& event) {
                return event.signal == signal;
            });
    }

private:
    mutable std::mutex mutex_;
    std::vector<SignalEvent> events_;
};

/**
 * 信号钩子综合测试类
 * 测试信号处理、回调机制等功能
 */
class SignalHookComprehensiveTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 初始化测试环境
        signal_hook_ = &SignalHook::getInstance();
        event_recorder_ = std::make_unique<SignalEventRecorder>();
        
        // 清除之前的处理器
        signal_hook_->clearAllHandlers();
        event_recorder_->clear();
        
        // 测试信号列表（使用用户定义信号避免干扰系统）
        test_signals_ = {SIGUSR1, SIGUSR2};
    }

    void TearDown() override {
        // 清理测试环境
        signal_hook_->clearAllHandlers();
        event_recorder_->clear();
    }

    SignalHook* signal_hook_;
    std::unique_ptr<SignalEventRecorder> event_recorder_;
    std::vector<int> test_signals_;
};

/**
 * 测试基本的信号处理器注册和注销
 */
TEST_F(SignalHookComprehensiveTest, TestBasicHandlerRegistration) {
    std::atomic<int> signal_count(0);
    
    // 注册信号处理器
    bool success = signal_hook_->registerHandler(SIGUSR1, [&signal_count](int signal) {
        signal_count.fetch_add(1);
    });
    
    EXPECT_TRUE(success);
    EXPECT_TRUE(signal_hook_->isHandlerRegistered(SIGUSR1));
    EXPECT_EQ(signal_hook_->getHandlerCount(), 1);
    
    // 触发信号处理
    signal_hook_->triggerHandler(SIGUSR1);
    EXPECT_EQ(signal_count.load(), 1);
    
    // 注销信号处理器
    bool unregister_success = signal_hook_->unregisterHandler(SIGUSR1);
    EXPECT_TRUE(unregister_success);
    EXPECT_FALSE(signal_hook_->isHandlerRegistered(SIGUSR1));
    EXPECT_EQ(signal_hook_->getHandlerCount(), 0);
}

/**
 * 测试多个信号处理器
 */
TEST_F(SignalHookComprehensiveTest, TestMultipleHandlers) {
    std::atomic<int> usr1_count(0);
    std::atomic<int> usr2_count(0);
    
    // 注册多个信号处理器
    bool success1 = signal_hook_->registerHandler(SIGUSR1, [&usr1_count](int signal) {
        usr1_count.fetch_add(1);
    });
    
    bool success2 = signal_hook_->registerHandler(SIGUSR2, [&usr2_count](int signal) {
        usr2_count.fetch_add(1);
    });
    
    EXPECT_TRUE(success1);
    EXPECT_TRUE(success2);
    EXPECT_EQ(signal_hook_->getHandlerCount(), 2);
    
    // 分别触发信号
    signal_hook_->triggerHandler(SIGUSR1);
    signal_hook_->triggerHandler(SIGUSR2);
    signal_hook_->triggerHandler(SIGUSR1);
    
    EXPECT_EQ(usr1_count.load(), 2);
    EXPECT_EQ(usr2_count.load(), 1);
}

/**
 * 测试信号处理器的参数传递
 */
TEST_F(SignalHookComprehensiveTest, TestHandlerParameters) {
    std::vector<int> received_signals;
    std::mutex signals_mutex;
    
    // 注册记录信号的处理器
    signal_hook_->registerHandler(SIGUSR1, [&received_signals, &signals_mutex](int signal) {
        std::lock_guard<std::mutex> lock(signals_mutex);
        received_signals.push_back(signal);
    });
    
    // 触发多次信号
    for (int i = 0; i < 5; ++i) {
        signal_hook_->triggerHandler(SIGUSR1);
    }
    
    // 验证接收到的信号
    std::lock_guard<std::mutex> lock(signals_mutex);
    EXPECT_EQ(received_signals.size(), 5);
    for (int signal : received_signals) {
        EXPECT_EQ(signal, SIGUSR1);
    }
}

/**
 * 测试信号处理器的异常处理
 */
TEST_F(SignalHookComprehensiveTest, TestHandlerExceptionHandling) {
    std::atomic<int> normal_count(0);
    std::atomic<int> exception_count(0);
    
    // 注册会抛出异常的处理器
    signal_hook_->registerHandler(SIGUSR1, [&exception_count](int signal) {
        exception_count.fetch_add(1);
        throw std::runtime_error("测试异常");
    });
    
    // 注册正常的处理器
    signal_hook_->registerHandler(SIGUSR2, [&normal_count](int signal) {
        normal_count.fetch_add(1);
    });
    
    // 触发异常处理器（应该不会崩溃）
    try {
        signal_hook_->triggerHandler(SIGUSR1);
    } catch (...) {
        // 捕获异常，确保不会影响其他处理器
    }
    
    // 触发正常处理器
    signal_hook_->triggerHandler(SIGUSR2);
    
    EXPECT_EQ(exception_count.load(), 1);
    EXPECT_EQ(normal_count.load(), 1);
}

/**
 * 测试信号事件记录功能
 */
TEST_F(SignalHookComprehensiveTest, TestSignalEventRecording) {
    // 注册记录事件的处理器
    signal_hook_->registerHandler(SIGUSR1, [this](int signal) {
        event_recorder_->recordSignal(signal);
    });
    
    signal_hook_->registerHandler(SIGUSR2, [this](int signal) {
        event_recorder_->recordSignal(signal);
    });
    
    // 触发多个信号
    signal_hook_->triggerHandler(SIGUSR1);
    signal_hook_->triggerHandler(SIGUSR2);
    signal_hook_->triggerHandler(SIGUSR1);
    
    // 验证事件记录
    EXPECT_EQ(event_recorder_->getEventCount(), 3);
    EXPECT_EQ(event_recorder_->getEventCount(SIGUSR1), 2);
    EXPECT_EQ(event_recorder_->getEventCount(SIGUSR2), 1);
    
    auto events = event_recorder_->getEvents();
    EXPECT_EQ(events.size(), 3);
    EXPECT_EQ(events[0].signal, SIGUSR1);
    EXPECT_EQ(events[1].signal, SIGUSR2);
    EXPECT_EQ(events[2].signal, SIGUSR1);
}

/**
 * 测试信号处理的时间特征
 */
TEST_F(SignalHookComprehensiveTest, TestSignalTimingCharacteristics) {
    std::vector<std::chrono::system_clock::time_point> timestamps;
    std::mutex timestamps_mutex;
    
    // 注册记录时间戳的处理器
    signal_hook_->registerHandler(SIGUSR1, [&timestamps, &timestamps_mutex](int signal) {
        std::lock_guard<std::mutex> lock(timestamps_mutex);
        timestamps.push_back(std::chrono::system_clock::now());
    });
    
    auto start = std::chrono::system_clock::now();
    
    // 快速触发多个信号
    for (int i = 0; i < 10; ++i) {
        signal_hook_->triggerHandler(SIGUSR1);
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    
    auto end = std::chrono::system_clock::now();
    
    // 验证时间戳
    std::lock_guard<std::mutex> lock(timestamps_mutex);
    EXPECT_EQ(timestamps.size(), 10);
    
    // 验证时间戳顺序
    for (size_t i = 1; i < timestamps.size(); ++i) {
        EXPECT_GE(timestamps[i], timestamps[i-1]);
    }
    
    // 验证总时间范围
    EXPECT_GE(timestamps.front(), start);
    EXPECT_LE(timestamps.back(), end);
}

/**
 * 测试多线程环境下的信号处理
 */
TEST_F(SignalHookComprehensiveTest, TestMultiThreadSignalHandling) {
    const int num_threads = 4;
    const int signals_per_thread = 25;
    std::atomic<int> total_signals(0);
    std::vector<std::thread::id> handler_thread_ids;
    std::mutex thread_ids_mutex;
    
    // 注册记录线程ID的处理器
    signal_hook_->registerHandler(SIGUSR1, [&total_signals, &handler_thread_ids, &thread_ids_mutex](int signal) {
        total_signals.fetch_add(1);
        std::lock_guard<std::mutex> lock(thread_ids_mutex);
        handler_thread_ids.push_back(std::this_thread::get_id());
    });
    
    std::vector<std::thread> threads;
    
    // 多个线程同时触发信号
    for (int t = 0; t < num_threads; ++t) {
        threads.emplace_back([this, signals_per_thread]() {
            for (int i = 0; i < signals_per_thread; ++i) {
                signal_hook_->triggerHandler(SIGUSR1);
                std::this_thread::sleep_for(std::chrono::microseconds(100));
            }
        });
    }
    
    // 等待所有线程完成
    for (auto& thread : threads) {
        thread.join();
    }
    
    // 验证结果
    EXPECT_EQ(total_signals.load(), num_threads * signals_per_thread);
    
    std::lock_guard<std::mutex> lock(thread_ids_mutex);
    EXPECT_EQ(handler_thread_ids.size(), num_threads * signals_per_thread);
    
    std::cout << "多线程信号处理测试: " << total_signals.load() 
              << " 个信号被处理" << std::endl;
}

/**
 * 测试信号处理器的性能特征
 */
TEST_F(SignalHookComprehensiveTest, TestSignalHandlerPerformance) {
    const int signal_count = 10000;
    std::atomic<int> processed_count(0);
    
    // 注册简单的计数处理器
    signal_hook_->registerHandler(SIGUSR1, [&processed_count](int signal) {
        processed_count.fetch_add(1);
    });
    
    auto start = std::chrono::high_resolution_clock::now();
    
    // 快速触发大量信号
    for (int i = 0; i < signal_count; ++i) {
        signal_hook_->triggerHandler(SIGUSR1);
    }
    
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
    
    // 验证性能
    EXPECT_EQ(processed_count.load(), signal_count);
    EXPECT_LT(duration.count(), 1000000); // 应该在1秒内完成
    
    double avg_time = static_cast<double>(duration.count()) / signal_count;
    std::cout << "信号处理性能: " << signal_count << " 个信号耗时 " 
              << duration.count() << " 微秒" << std::endl;
    std::cout << "平均每个信号处理时间: " << avg_time << " 微秒" << std::endl;
}

/**
 * 测试信号处理器的重复注册
 */
TEST_F(SignalHookComprehensiveTest, TestHandlerReregistration) {
    std::atomic<int> first_handler_count(0);
    std::atomic<int> second_handler_count(0);
    
    // 注册第一个处理器
    signal_hook_->registerHandler(SIGUSR1, [&first_handler_count](int signal) {
        first_handler_count.fetch_add(1);
    });
    
    signal_hook_->triggerHandler(SIGUSR1);
    EXPECT_EQ(first_handler_count.load(), 1);
    EXPECT_EQ(second_handler_count.load(), 0);
    
    // 重新注册同一信号的处理器（应该覆盖之前的）
    signal_hook_->registerHandler(SIGUSR1, [&second_handler_count](int signal) {
        second_handler_count.fetch_add(1);
    });
    
    signal_hook_->triggerHandler(SIGUSR1);
    EXPECT_EQ(first_handler_count.load(), 1); // 不应该增加
    EXPECT_EQ(second_handler_count.load(), 1); // 应该增加
}

/**
 * 测试信号处理器的资源管理
 */
TEST_F(SignalHookComprehensiveTest, TestHandlerResourceManagement) {
    std::atomic<int> destructor_count(0);
    
    {
        // 创建带有资源的处理器
        auto resource = std::make_shared<std::atomic<int>>();
        resource->store(42);
        
        signal_hook_->registerHandler(SIGUSR1, [resource, &destructor_count](int signal) {
            // 使用共享资源
            int value = resource->load();
            EXPECT_EQ(value, 42);
        });
        
        // 触发信号处理
        signal_hook_->triggerHandler(SIGUSR1);
        
        // resource 在这里应该还存在（被lambda捕获）
        EXPECT_EQ(resource->load(), 42);
    }
    
    // 触发信号处理（资源应该仍然有效）
    signal_hook_->triggerHandler(SIGUSR1);
    
    // 注销处理器
    signal_hook_->unregisterHandler(SIGUSR1);
    
    // 现在资源应该被释放了
}

/**
 * 测试信号处理的错误恢复
 */
TEST_F(SignalHookComprehensiveTest, TestSignalErrorRecovery) {
    std::atomic<int> success_count(0);
    std::atomic<int> error_count(0);
    
    // 注册可能失败的处理器
    signal_hook_->registerHandler(SIGUSR1, [&success_count, &error_count](int signal) {
        static int call_count = 0;
        call_count++;
        
        if (call_count % 3 == 0) {
            error_count.fetch_add(1);
            throw std::runtime_error("模拟处理错误");
        } else {
            success_count.fetch_add(1);
        }
    });
    
    // 触发多次信号，包括会出错的情况
    for (int i = 0; i < 10; ++i) {
        try {
            signal_hook_->triggerHandler(SIGUSR1);
        } catch (...) {
            // 忽略异常，继续处理
        }
    }
    
    // 验证错误恢复
    EXPECT_GT(success_count.load(), 0);
    EXPECT_GT(error_count.load(), 0);
    EXPECT_EQ(success_count.load() + error_count.load(), 10);
}

/**
 * 测试信号处理的优先级和顺序
 */
TEST_F(SignalHookComprehensiveTest, TestSignalPriorityAndOrdering) {
    std::vector<int> execution_order;
    std::mutex order_mutex;
    
    // 注册多个信号的处理器
    signal_hook_->registerHandler(SIGUSR1, [&execution_order, &order_mutex](int signal) {
        std::lock_guard<std::mutex> lock(order_mutex);
        execution_order.push_back(1);
    });
    
    signal_hook_->registerHandler(SIGUSR2, [&execution_order, &order_mutex](int signal) {
        std::lock_guard<std::mutex> lock(order_mutex);
        execution_order.push_back(2);
    });
    
    // 按特定顺序触发信号
    signal_hook_->triggerHandler(SIGUSR1);
    signal_hook_->triggerHandler(SIGUSR2);
    signal_hook_->triggerHandler(SIGUSR1);
    signal_hook_->triggerHandler(SIGUSR2);
    
    // 验证执行顺序
    std::lock_guard<std::mutex> lock(order_mutex);
    EXPECT_EQ(execution_order.size(), 4);
    EXPECT_EQ(execution_order[0], 1);
    EXPECT_EQ(execution_order[1], 2);
    EXPECT_EQ(execution_order[2], 1);
    EXPECT_EQ(execution_order[3], 2);
}

/**
 * 测试完整的信号钩子工作流程
 */
TEST_F(SignalHookComprehensiveTest, TestCompleteWorkflow) {
    // 模拟完整的信号处理应用场景
    
    // 1. 初始化信号处理系统
    std::atomic<bool> shutdown_requested(false);
    std::atomic<int> data_received_count(0);
    std::atomic<int> error_count(0);
    
    // 2. 注册不同类型的信号处理器
    
    // 关闭信号处理器
    signal_hook_->registerHandler(SIGUSR1, [&shutdown_requested](int signal) {
        std::cout << "收到关闭信号，准备退出..." << std::endl;
        shutdown_requested.store(true);
    });
    
    // 数据处理信号处理器
    signal_hook_->registerHandler(SIGUSR2, [&data_received_count, this](int signal) {
        data_received_count.fetch_add(1);
        event_recorder_->recordSignal(signal);
    });
    
    // 3. 模拟应用运行
    std::thread worker_thread([&]() {
        while (!shutdown_requested.load()) {
            // 模拟数据处理
            signal_hook_->triggerHandler(SIGUSR2);
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            
            // 模拟错误情况
            if (data_received_count.load() > 0 && data_received_count.load() % 10 == 0) {
                try {
                    throw std::runtime_error("模拟处理错误");
                } catch (...) {
                    error_count.fetch_add(1);
                }
            }
        }
    });
    
    // 4. 运行一段时间后发送关闭信号
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    signal_hook_->triggerHandler(SIGUSR1);
    
    // 5. 等待工作线程结束
    worker_thread.join();
    
    // 6. 验证结果
    EXPECT_TRUE(shutdown_requested.load());
    EXPECT_GT(data_received_count.load(), 0);
    EXPECT_GT(event_recorder_->getEventCount(), 0);
    
    // 7. 生成处理报告
    auto events = event_recorder_->getEvents();
    int usr1_events = event_recorder_->getEventCount(SIGUSR1);
    int usr2_events = event_recorder_->getEventCount(SIGUSR2);
    
    std::cout << "信号处理工作流程完成:" << std::endl;
    std::cout << "- 处理了 " << data_received_count.load() << " 个数据信号" << std::endl;
    std::cout << "- 记录了 " << events.size() << " 个信号事件" << std::endl;
    std::cout << "- SIGUSR1 事件: " << usr1_events << " 个" << std::endl;
    std::cout << "- SIGUSR2 事件: " << usr2_events << " 个" << std::endl;
    std::cout << "- 处理错误: " << error_count.load() << " 个" << std::endl;
    
    // 8. 清理资源
    signal_hook_->clearAllHandlers();
    
    EXPECT_EQ(signal_hook_->getHandlerCount(), 0);
} 